package com.zy.design.pattern.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zhaoyi
 * @date 2021/4/8 15:58
 */
public class ProxyFactory {

    //1 反射使用代理目标类(被代理，解耦的目标类)
    private Object target;

    //2 可以通过构造器动态设置被代理目标类，以便于调用指定方法
    public ProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //System.out.println(proxy.getClass());//代理com.sun.proxy.$Proxy0
                        System.out.println("before ===========" + method.getName());
                        Object obj = method.invoke(target, args);
                        System.out.println("after ~~~~~~~~~~~~" + method.getName());
                        return obj;
                    }


                });

    }


}
